package entity

import (
	"errors"

	"go_iot/apps/base"
	"go_iot/pkg/global"
	"go_iot/pkg/util"
	"time"
)

type User struct {
	base.Base
	CreatedAt    time.Time `json:"created" gorm:"column:created_at"`
	NickName     string    `json:"name" validate:"required" gorm:"column:nickname"`
	Account      string    `json:"account" validate:"required" gorm:"column:account"`
	Password     string    `json:"password,omitempty" validate:"required" gorm:"-"`
	HashPassword string    `json:"-" gorm:"column:hash_password"`
	Salt         string    `json:"-" gorm:"column:salt"`
	ProjectId    int       `json:"project" gorm:"column:project_id"`
	Phone        string    `json:"phone" validate:"required" gorm:"column:phone"`
	Email        string    `json:"email" validate:"required,email" gorm:"column:email"`
}

func (User) TableName() string {
	return "users"
}

func CheckUser(account, password string) (User, error) {
	var u User

	if account == "" || password == "" {
		return u, errors.New("账号密码不能为空")
	}
	user, err := GetUserByAccount(u.Account)
	if err != nil {

		return user, err
	}
	if util.VerifyPassword(password, user.HashPassword, user.Salt) {

		return user, nil
	}

	return u, errors.New("账号或者密码不正确")
}

func GetUserByAccount(account string) (User, error) {
	var u = User{
		Account: account,
	}
	err := global.Db.First(&u).Error

	return u, base.WrapError(err)
}
